import "./reTotal.css";
import { useEffect, useRef, useState } from "react";
import * as echarts from "echarts";
import { Select, Radio } from "antd";
const plainOptions = ["月", "年"];
const { Option } = Select;
const optionsWithDisabled = [
  {
    label: "月",
    value: "1",
  },
  {
    label: "年",
    value: "2",
  },
];
const ReTotal = () => {
  const chartRef = useRef(null);
  const chartRefOne = useRef(null);
  const chartRefTwo = useRef(null);
  const chartRefFour = useRef(null);
  let [xData, setxData] = useState([]);

  let [value, setvalue] = useState('1');

  const change = (e) => {
    // echarts.init(document.getElementById('chartRef')).dispose(); // 销毁实例
    // echarts.init(document.getElementById('chartRefFour')).dispose(); // 销毁实例
    console.log(e, "ee");
    setvalue(e);

    // setTimeout(() => {
    //   if (e === "月") {
    //     getWeekList();
    //   } else {
    //     getYear();
    //   }
    // }, 200);
  };

  const changeTwo = (e) => {
    setvalue(e.target.value);
    // let time = 1;
    // console.log(e, "ewwe");
    // setTimeout(() => {
    //   if (e === "月") {
    //     time == 1 && getWeekList();
    //   } else {
    //     time == 1 && getYear();
    //   }
    //   time++;
    // }, 200);
  };

  useEffect(() => {
    getWeekList();
    drawCircleOne();
    drawCircleTwo();
    getYear();
  }, []);

  // 获取当天0点的时间戳
  const getStartTime = (time) => {
    const nowTimeDate = new Date(time);
    return nowTimeDate.setHours(0, 0, 0, 0);
  };
  // 时间戳转日期格式
  const timestampToTime = (timestamp) => {
    var date = new Date(timestamp);
    var Y = date.getFullYear() + "-";
    var M =
      (date.getMonth() + 1 < 10
        ? "0" + (date.getMonth() + 1)
        : date.getMonth() + 1) + "-";
    var D = date.getDate();
    // var h = date.getHours() + ':';
    // var m = date.getMinutes() + ':';
    // var s = date.getSeconds();
    // return Y + M + D + ' ' + h + m + s
    return Y + M + D;
  };
  // 获取一周的日期
  const getWeekList = async (type) => {
    let week = [];
    for (var i = 0; i < 7; i++) {
      let weekObj = {
        // name: this.weekName[i],
        date: "",
        // timeStamp: '',
      };
      week.push(weekObj);
    }
    let today = getStartTime(Number(new Date())); // 当天时间戳
    let today_week = new Date().getDay(); // 当天星期几
    if (today_week == 0) {
      // 若当天为周日
      week[6].timeStamp = today;
    } else {
      week[today_week - 1].timeStamp = today;
    }

    var leftNum = today_week - 1; // 本周内今天的前几天的数量
    var rightNum = 7 - today_week; // 本周内今天的后几天的数量

    for (var left = 0; left < leftNum; left++) {
      week[left].timeStamp =
        today - (today_week - left - 1) * 1000 * 60 * 60 * 24;
    }
    for (var right = 0; right < rightNum; right++) {
      week[right + today_week].timeStamp =
        today + (right + 1) * 1000 * 60 * 60 * 24;
    }
    week.map((el) => {
      el.date = timestampToTime(el.timeStamp);
    });
    week.splice(week.length - 1, 1);
    let newDate = timestampToTime(new Date());
    week.unshift({
      date: newDate,
    });
    let copyWeek = [];
    for (let i = 0; i < week.length; i++) {
      await copyWeek.push(week[i].date);
    }
    console.log(copyWeek, "copyWeekcopyWeekcopyWeek");
    let copyJsonData = JSON.parse(localStorage.getItem("Data"));
    let length = copyJsonData.length;
    let inCome = [];
    let outCome = [];

    let one = 0;
    let two = 0;
    let three = 0;
    let four = 0;
    let five = 0;
    let six = 0;
    let seven = 0;

    let oneout = 0;
    let twoout = 0;
    let threeout = 0;
    let fourout = 0;
    let fiveout = 0;
    let sixout = 0;
    let sevenout = 0;

    for (let i = 0; i < 7; i++) {
      for (let k = 0; k < copyJsonData.length; k++) {
        if (
          (copyJsonData[k].date.split(" ")[0].split("-")[2] ==
          copyWeek[0].split("-")[2] ) && k==i
        ) {
          if (parseInt(copyJsonData[i].money) > 0) {
            one = one + parseInt(copyJsonData[i].money);
          } else {
            oneout = oneout + parseInt(copyJsonData[i].money);
          }
        }

        if (
          (copyJsonData[k].date.split(" ")[0].split("-")[2] ==
          copyWeek[1].split("-")[2] ) && k==i
        ) {
          if (parseInt(copyJsonData[i].money) > 0) {
            two = two + parseInt(copyJsonData[i].money);
          } else {
            twoout = twoout + parseInt(copyJsonData[i].money);
          }
        }

        if (
          (copyJsonData[k].date.split(" ")[0].split("-")[2] ==
          copyWeek[2].split("-")[2] ) && k==i
        ) {
          if (parseInt(copyJsonData[i].money) > 0) {
            three = three + parseInt(copyJsonData[i].money);
          } else {
            threeout = threeout + parseInt(copyJsonData[i].money);
          }
        }

        if (
          (copyJsonData[k].date.split(" ")[0].split("-")[2] ==
          copyWeek[3].split("-")[2] ) && k==i
        ) {
          if (parseInt(copyJsonData[i].money) > 0) {
            four = four + parseInt(copyJsonData[i].money);
          } else {
            fourout = fourout + parseInt(copyJsonData[i].money);
          }
        }

        if (
          (copyJsonData[k].date.split(" ")[0].split("-")[2] ==
          copyWeek[4].split("-")[2] ) && k==i
        ) {
          if (parseInt(copyJsonData[i].money) > 0) {
            five = five + parseInt(copyJsonData[i].money);
          } else {
            fiveout = fiveout + parseInt(copyJsonData[i].money);
          }
        }

        if (
          (copyJsonData[k].date.split(" ")[0].split("-")[2] ==
          copyWeek[5].split("-")[2] ) && k==i
        ) {
          if (parseInt(copyJsonData[k].money) > 0) {
            six = six + parseInt(copyJsonData[i].money);
          } else {
            sixout = sixout + parseInt(copyJsonData[i].money);
          }
        }

        if (
          (copyJsonData[k].date.split(" ")[0].split("-")[2] ==
          copyWeek[6].split("-")[2] ) && k==i
        ) {
          if (parseInt(copyJsonData[k].money) > 0) {
            seven = seven + parseInt(copyJsonData[i].money);
          } else {
            sevenout = sevenout + parseInt(copyJsonData[i].money);
          }
        }
      }
    }

    inCome.push(one)
    inCome.push(two)
    inCome.push(three)
    inCome.push(four)
    inCome.push(five)
    inCome.push(six)
    inCome.push(seven)

    outCome.push(oneout)
    outCome.push(twoout)
    outCome.push(threeout)
    outCome.push(fourout)
    outCome.push(fiveout)
    outCome.push(sixout)
    outCome.push(sevenout)
    


    console.log(one, "inComeinCome");
    console.log(oneout, "outComeoutCome");

    // if (copyJsonData.length > copyWeek.length) {
    //   for (let i = 0; i < copyJsonData.length; i++) {
    //     for (let k = 0; k < copyWeek.length; k++) {
    //       if (copyJsonData[k].money > 0) {
    //         await inCome.push(copyJsonData[k].money);
    //       } else {
    //         await outCome.push(copyJsonData[k].money);
    //       }
    //     }
    //   }
    // } else {
    //   for (let i = 0; i < copyWeek.length; i++) {
    //     for (let k = 0; k < copyJsonData.length; k++) {
    //       if (copyJsonData[k].money > 0) {
    //         await inCome.push(copyJsonData[k].money);
    //       } else {
    //         await outCome.push(copyJsonData[k].money);
    //       }
    //     }
    //   }
    // }
    setTimeout(() => {
      let chartInstance = echarts.init(chartRef.current);
      const option = {
        title: {
          text: "趋势周统计图",
        },

        tooltip: {
          trigger: "axis",
        },

        legend: {
          data: ["收入", "支出"],
        },

        toolbox: {
          show: true,
        },

        xAxis: {
          type: "category",

          boundaryGap: false,

          data: copyWeek,
        },

        yAxis: {
          type: "value",

          axisLabel: {
            formatter: "{value} 元",
          },
        },

        series: [
          {
            name: "收入",

            type: "line",

            data: inCome,
          },

          {
            name: "支出",

            type: "line",

            data: outCome,
          },
        ],
      };
      chartInstance.setOption(option);
    }, 200);
  };

  const getYear = () => {
    let copyJsonData = JSON.parse(localStorage.getItem("Data"));
    let length = copyJsonData.length;
    let yiyue = 0;
    let eryue = 0;
    let sanyue = 0;
    let siyue = 0;
    let wuyue = 0;
    let liuyue = 0;
    let qiyue = 0;
    let bayue = 0;
    let jiuyue = 0;
    let shiyue = 0;
    let shiyiyue = 0;
    let shieryue = 0;

    let yiyueout = 0;
    let eryueout = 0;
    let sanyueout = 0;
    let siyueout = 0;
    let wuyueout = 0;
    let liuyueout = 0;
    let qiyueout = 0;
    let bayueout = 0;
    let jiuyueout = 0;
    let shiyueout = 0;
    let shiyiyueout = 0;
    let shieryueout = 0;

    let finall = [];
    let finallOut = [];

    for (let i = 0; i < 12; i++) {
      for (let k = 0; k < copyJsonData.length; k++) {
        if (copyJsonData[k].date.charAt(6) == "1" && i == 0) {
          if (parseInt(copyJsonData[k].money) > 0) {
            yiyue = yiyue + parseInt(copyJsonData[k].money);
          } else {
            yiyueout = yiyueout + parseInt(copyJsonData[k].money);
          }
        }
        if (copyJsonData[k].date.charAt(6) == "2" && i == 1) {
          if (parseInt(copyJsonData[k].money) > 0) {
            eryue = eryue + parseInt(copyJsonData[k].money);
          } else {
            eryueout = eryueout + parseInt(copyJsonData[k].money);
          }
        }
        if (copyJsonData[k].date.charAt(6) == "3" && i == 2) {
          if (parseInt(copyJsonData[k].money) > 0) {
            sanyue = sanyue + parseInt(copyJsonData[k].money);
          } else {
            sanyueout = sanyueout + parseInt(copyJsonData[k].money);
          }
        }
        if (copyJsonData[k].date.charAt(6) == "4" && i == 3) {
          if (parseInt(copyJsonData[k].money) > 0) {
            siyue = siyue + parseInt(copyJsonData[k].money);
          } else {
            siyueout = siyueout + parseInt(copyJsonData[k].money);
          }
        }
        if (copyJsonData[k].date.charAt(6) == "5" && i == 4) {
          if (parseInt(copyJsonData[k].money) > 0) {
            wuyue = wuyue + parseInt(copyJsonData[k].money);
          } else {
            wuyueout = wuyueout + parseInt(copyJsonData[k].money);
          }
        }
        if (copyJsonData[k].date.charAt(6) == "6" && i == 5) {
          if (parseInt(copyJsonData[k].money) > 0) {
            liuyue = liuyue + parseInt(copyJsonData[k].money);
          } else {
            liuyueout = liuyueout + parseInt(copyJsonData[k].money);
          }
        }
        if (copyJsonData[k].date.charAt(6) == "7" && i == 6) {
          if (parseInt(copyJsonData[k].money) > 0) {
            qiyue = qiyue + parseInt(copyJsonData[k].money);
          } else {
            qiyueout = qiyueout + parseInt(copyJsonData[k].money);
          }
        }
        if (copyJsonData[k].date.charAt(6) == "8" && i == 7) {
          if (parseInt(copyJsonData[k].money) > 0) {
            bayue = bayue + parseInt(copyJsonData[k].money);
          } else {
            bayueout = bayueout + parseInt(copyJsonData[k].money);
          }
        }
        if (copyJsonData[k].date.charAt(6) == "9" && i == 8) {
          if (parseInt(copyJsonData[k].money) > 0) {
            jiuyue = jiuyue + parseInt(copyJsonData[k].money);
          } else {
            jiuyueout = jiuyueout + parseInt(copyJsonData[k].money);
          }
        }
        if (copyJsonData[k].date.charAt(6) == "0" && i == 9) {
          if (parseInt(copyJsonData[k].money) > 0) {
            shiyue = shiyue + parseInt(copyJsonData[k].money);
          } else {
            shiyueout = shiyueout + parseInt(copyJsonData[k].money);
          }
        }
        if (copyJsonData[k].date.charAt(6) == "1" && i == 10) {
          if (parseInt(copyJsonData[k].money) > 0) {
            shiyiyue = shiyiyue + parseInt(copyJsonData[k].money);
          } else {
            shiyiyueout = shiyiyueout + parseInt(copyJsonData[k].money);
          }
        }
        if (copyJsonData[k].date.charAt(6) == "2" && i == 11) {
          if (parseInt(copyJsonData[k].money) > 0) {
            shieryue = shieryue + parseInt(copyJsonData[k].money);
          } else {
            shieryueout = shieryueout + parseInt(copyJsonData[k].money);
          }
        }
      }
    }
    finall.push(yiyue);
    finall.push(eryue);
    finall.push(sanyue);
    finall.push(siyue);
    finall.push(wuyue);
    finall.push(liuyue);
    finall.push(qiyue);
    finall.push(bayue);
    finall.push(jiuyue);
    finall.push(shiyue);
    finall.push(shiyiyue);
    finall.push(shieryue);

    finallOut.push(yiyueout);
    finallOut.push(eryueout);
    finallOut.push(sanyueout);
    finallOut.push(siyueout);
    finallOut.push(wuyueout);
    finallOut.push(liuyueout);
    finallOut.push(qiyueout);
    finallOut.push(bayueout);
    finallOut.push(jiuyueout);
    finallOut.push(shiyueout);
    finallOut.push(shiyiyueout);
    finallOut.push(shieryueout);

    let chartInstance = echarts.init(chartRefFour.current);
    const option = {
      title: {
        text: "趋势月统计图",
      },

      tooltip: {
        trigger: "axis",
      },

      legend: {
        data: ["收入", "支出"],
      },

      toolbox: {
        show: true,
      },

      xAxis: {
        type: "category",

        boundaryGap: false,

        data: [
          "1月",
          "2月",
          "3月",
          "4月",
          "5月",
          "6月",
          "7月",
          "8月",
          "9月",
          "10月",
          "11月",
          "12月",
        ],
      },

      yAxis: {
        type: "value",

        axisLabel: {
          formatter: "{value} 元",
        },
      },

      series: [
        {
          name: "收入",

          type: "line",

          data: finall,
        },

        {
          name: "支出",

          type: "line",

          data: finallOut,
        },
      ],
    };
    chartInstance.setOption(option);
  };

  const drawCircleOne = () => {
    let copyJsonData = JSON.parse(localStorage.getItem("Data"));
    let zaocan = 0;
    let dianzi = 0;
    let licai = 0;
    let yiwu = 0;
    for (let i = 0; i < copyJsonData.length; i++) {
      if (copyJsonData[i].type === "早餐") {
        zaocan += parseInt(copyJsonData[i].money);
      }
      if (copyJsonData[i].type === "电子") {
        dianzi += parseInt(copyJsonData[i].money);
      }
      if (copyJsonData[i].type === "理财") {
        licai += parseInt(copyJsonData[i].money);
      }
      if (copyJsonData[i].type === "衣物") {
        yiwu += parseInt(copyJsonData[i].money);
      }
    }
    console.log(zaocan, "zaocan");
    setTimeout(() => {
      let chartInstance = echarts.init(chartRefOne.current);
      const option = {
        title: {
          text: "支出",
          left: "center",
          top: "center",
        },
        tooltip: {
          //提示框组件
          trigger: "item", //item数据项图形触发，主要在散点图，饼图等无类目轴的图表中使用。
          axisPointer: {
            // 坐标轴指示器，坐标轴触发有效
            type: "shadow", // 默认为直线，可选为：'line' | 'shadow'
          },
          formatter: "{c}元", //{a}（系列名称），{b}（数据项名称），{c}（数值）, {d}（百分比）
        },
        legend: {
          data: ["早餐", "电子", "理财", "衣物"],
        },
        series: [
          {
            type: "pie",
            data: [
              {
                value: Math.abs(zaocan) === 0 ? 0 : Math.abs(zaocan),
                name: "早餐",
              },
              {
                value: Math.abs(dianzi) === 0 ? 0 : Math.abs(dianzi),
                name: "电子",
              },
              {
                value: Math.abs(licai) === 0 ? 0 : Math.abs(licai),
                name: "理财",
              },
              {
                value: Math.abs(yiwu) === 0 ? 0 : Math.abs(yiwu),
                name: "衣物",
              },
            ],
          },
        ],
      };
      chartInstance.setOption(option);
    }, 20);
  };

  const drawCircleTwo = () => {
    let copyJsonData = JSON.parse(localStorage.getItem("Data"));
    let gongzi = 0;
    let qita = 0;
    for (let i = 0; i < copyJsonData.length; i++) {
      if (copyJsonData[i].type === "工资") {
        gongzi += parseInt(copyJsonData[i].money);
      }
      if (copyJsonData[i].type === "其他") {
        qita += parseInt(copyJsonData[i].money);
      }
    }
    setTimeout(() => {
      let chartInstance = echarts.init(chartRefTwo.current);
      const option = {
        title: {
          text: "收入",
          left: "center",
          top: "center",
        },
        tooltip: {
          //提示框组件
          trigger: "item", //item数据项图形触发，主要在散点图，饼图等无类目轴的图表中使用。
          axisPointer: {
            // 坐标轴指示器，坐标轴触发有效
            type: "shadow", // 默认为直线，可选为：'line' | 'shadow'
          },
          formatter: "{c}元", //{a}（系列名称），{b}（数据项名称），{c}（数值）, {d}（百分比）
        },
        legend: {
          data: ["工资", "其他"],
        },
        series: [
          {
            type: "pie",
            data: [
              {
                value: Math.abs(gongzi) === 0 ? 0 : Math.abs(gongzi),
                name: "工资",
              },
              {
                value: Math.abs(qita) === 0 ? 0 : Math.abs(qita),
                name: "其他",
              },
            ],
          },
        ],
      };
      chartInstance.setOption(option);
    }, 20);
  };
  return (
    <div className="reTotal">
      <div className="flexTwo">
        <Select
          style={{ width: 120 }}
          // allowClear
          value={value}
          onChange={change}
        >
          <Option value="1">月</Option>
          <Option value="2">年</Option>
        </Select>
        <Radio.Group
          options={optionsWithDisabled}
          optionType="button"
          value={value}
          buttonStyle="solid"
          onChange={changeTwo}
        />
      </div>
      <div style={{ textAlign: "center" }}>
          <div
            ref={chartRef}
            style={{ height: "400px", width: "1000px", display: (value==='1') ? "block" : "none" }}
          ></div>
          <div
            ref={chartRefFour}
            style={{ height: "400px", width: "1000px", display: (value==='2') ? "block" : "none" }}
          ></div>
        <h2>分类支出收入统计</h2>
        <div className="flex">
          <div
            ref={chartRefOne}
            style={{ height: "400px", width: "500px" }}
          ></div>
          <div
            ref={chartRefTwo}
            style={{ height: "400px", width: "500px" }}
          ></div>
        </div>
      </div>
    </div>
  );
};

export default ReTotal;
